<?php
session_start();
include '../conn.php'; // 确保这是正确的路径到你的数据库连接文件


// 检查是否设置了所有必要的参数
if (!isset($_REQUEST['uid']) || !isset($_REQUEST['gid'])) {
	echo json_encode(array("error" => "非法访问，缺少参数。"));
    echo "非法访问！";
    exit;
}
$uid = $_REQUEST['uid'];
// print_r($uid);
$gid = $_REQUEST['gid'];
// print_r($gid);
// 检查用户是否存在
$sql = "SELECT * FROM user WHERE id = " . $uid;
$result = $conn->query($sql);

// 判断是否已经添加进来了
$checkCollectSql = "SELECT * FROM dianzan WHERE user_id = " . $uid . " AND good_id = " . $gid;
// 执行的sql语句
// echo "SQL: " . $checkCollectSql;
$resultCollect = $conn->query($checkCollectSql);

if ($result && $result->num_rows > 0) {
    // 获取查询结果的第一行
    $row = $result->fetch_assoc();	
	// 打印结果
	// print_r($row['uname']);
	
	if ($resultCollect && $resultCollect->num_rows > 0) {
		// 进行删除这条数据 
		$deleteSql = "DELETE FROM dianzan WHERE user_id = ".$uid. " AND good_id = " .$gid;
		$resultDelete = $conn->query($deleteSql);
		if($resultDelete){
			echo json_encode(array("message" => "取消点赞成功","status" => "cancelled"),JSON_UNESCAPED_UNICODE);
		}
		// echo "<script>alert('已经点赞了！'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";
		// echo "已经点赞了！";
	}else{
		// 添加收藏
		$sql2 = "INSERT INTO dianzan (good_id, user_id) VALUES (".$gid.", ".$uid.")";
		// echo "SQL: " . $sql2;
		if ($conn->query($sql2)) {
			echo json_encode(array("message" => "点赞成功", "status" => "liked"),JSON_UNESCAPED_UNICODE);
			// echo "<script>alert('点赞成功！'); window.location.href = '../goods.php?id={$gid}&uid={$uid}';</script>";
			// echo "点赞成功！";
		  }else {
			echo "点赞失败";
		  }
	}
	
} else {
    echo "没有找到用户或查询失败";
}


?>